/**
 * @file my-tasks.js
 * @author fsc
 * @date 2018/12/26
 */

function getPaginationNav(current, total, navCount, callback) {
  function getLi(num, txt, active, click) {
    active = active || false;
    txt = txt || num;
    var li = $('<li></li>');
    if (active) {
      li.addClass('active');
    }
    //fsch time:12-21 11:20
    var a = $('<a  href="'+Urls.resolve('mlplatform:my_tasks') + '#' + num + '">' + txt + '</a>');
    a.click(function () {
      click(num);
    });
    li.append(a);
    return li;
  }

  function aroundCurrent(current, total, navCount) {
    var pages = [current];
    var halfNavCount = Math.ceil(navCount / 2);
    var minPage = Math.max(0, current - halfNavCount);
    var maxPage = Math.min(total + 1, current + halfNavCount);
    for (var i = current - 1; i > minPage; i--) {
      pages.unshift(i);
    }
    for (var j = current + 1; j < maxPage; j++) {
      pages.push(j);
    }

    if (pages.length < Math.min(navCount, total)) {
      if (maxPage - current < halfNavCount) {
        minPage = Math.max(0, maxPage - navCount - 1);
        for (i = pages[0] - 1; i > minPage; i--) {
          pages.unshift(i);
        }
      } else if (current - minPage < halfNavCount) {
        maxPage = Math.min(total + 1, minPage + navCount + 1);
        for (j = pages[pages.length - 1] + 1; j < maxPage; j++) {
          pages.push(j);
        }
      }
    }

    return pages;
  }

  navCount = navCount || 5;
  var nav = $('<nav></nav>'),
    ul = $('<ul class="pagination"></ul>');
  var pages = aroundCurrent(current, total, navCount);
  pages.forEach(function (value) {
    ul.append(getLi(value, value, value === current, callback));
  });
  if (current > 1) {
    ul.prepend(getLi(current - 1, '<i class="fa fa-angle-double-left"></i>', false, callback));
  }
  if (current < total) {
    ul.append(getLi(current + 1, '<i class="fa fa-angle-double-right"></i>', false, callback))
  }
  nav.append(ul);

  return nav;
}

function getMetaPanel(t) {
  var status;
  var result='— —';
  if(t.status==0){
    status=gettext("Unconducted");
  }
  else if (t.status==1){
    status=gettext("Running");
  }
  else if(t.status==2){
    status=gettext("Completed");
    // var result_con=t.result;
    // var reuslt_keys=Object.keys(result_con);
    // result='';
    // reuslt_keys.forEach(function(it){
    //     result+=it+' : '+result_con[it]+' ';
    // });
    // var link='<a target="_blank" href="' + Urls.resolve('mlplatform:view_task', {tid: t.id}) + '" title="' + gettext('Click to view details.') + '">,……</a>';
    // result=reuslt_keys[0]+':'+result_con[reuslt_keys[0]]+link;
    var link='<a target="_blank" href="' + Urls.resolve('mlplatform:view_task', {tid: t.id}) + '">'+gettext('Click to view details.')+'</a>';
    result=link;
  }
  else{
    status=gettext("Failure");
  }
  return '<div class="panel panel-default">' +
    '  <div class="panel-heading">' +
    '    <a target="_blank" href="' + Urls.resolve('mlplatform:view_task', {tid: t.id}) + '" title="' + gettext('View') + '">' + t.title + '</a>' +
    '    <div class="pull-right">' +
    '      <a role="button" onclick="deleteTask(\'' + t.id + '\',this)" title="' + gettext('Delete') + '"><i class="fa fa-trash"></i></a>' +
    '      <a target="_blank" href="' + Urls.resolve('mlplatform:view_task', {tid: t.id}) + '" title="' + gettext('View') + '"><i class="fa fa-external-link"></i></a>' +
    '    </div>' +
    '  </div>' +
    '  <div class="panel-body">' +
    // '    <div class="row">' +
    // '      <div class="col-sm-12">' +
    // '        <p><span class="dt">' + gettext('Title') + '</span><span class="dd">' + t.title + '</span></p>' +
    // '      </div>' +
    // '    </div>' +
    '    <div class="row">' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Author') + '</span><span class="dd">' + t.author + '</span></p>' +
    '      </div>' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Status') + '</span><span class="dd">' + status + '</span></p>' +
    '      </div>' +
    // '      <div class="col-sm-3">' +
    // '        <p><span class="dt">' + gettext('Submit Time') + '</span><span class="dd">' + t.pub_data + '</span></p>' +
    // '      </div>' +
    '    </div>' +
    '    <div class="row">' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Dataset') + '</span><span class="dd">' + t.dataset + '</span></p>' +
    '      </div>' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Algorithm') + '</span><span class="dd">' + t.algorithm + '</span></p>' +
    '      </div>' +
    '      <div class="col-sm-3">' +
    '        <p><span class="dt">' + gettext('Result') + '</span><span class="dd">' + result + '</span></p>' +
    '      </div>' +
    '    </div>' +
    '  </div>' +
    '</div>';
}

function deleteTask(did, that) {
  var panel = $(that).parents('.panel:first');
  $.showModal({
    title: gettext('Warning'),
    message: interpolate(gettext('Are you sure to delete "%s"'), [panel.find('.panel-heading').text()]),
    onOk: function () {
      $.ajax(Urls.resolve('mlplatform_api_v1:task_detail', {pk: did}), {
        method: 'DELETE'
      }).done(function () {
        panel.hide(500, function () {
          panel.remove();
        });
      });
    }
  });
}

function getAll(page, perPage) {
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve('mlplatform_api_v1:task_list_my'), {
    'page':page,
  }).done(function (resp) {
      $("#ta-count").html(resp.data.count);
    var taScope = $('#ta-scope');
    taScope.empty();
    resp.data.results.forEach(function (it) {
      taScope.append(getMetaPanel(it));
    });
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $pScope = $('#ta-pagination-scope');
      $pScope.empty();
      $pScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getAll(pageNo, perPage);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function getAllSort(page, perPage,isAsc) {
  var url='mlplatform_api_v1:task_list_my_des';
  if(isAsc)
    url='mlplatform_api_v1:task_list_my_asc';
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve(url), {
    'page':page,
  }).done(function (resp) {
    var taScope = $('#ta-scope');
    taScope.empty();
    resp.data.results.forEach(function (it) {
      taScope.append(getMetaPanel(it));
    });
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $pScope = $('#ta-pagination-scope');
      $pScope.empty();
      $pScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getAllSort(pageNo, perPage,isAsc);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function getUnconducted(page, perPage) {
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve('mlplatform_api_v1:task_list_my_st_unc'), {
    'page':page,
  }).done(function (resp) {
    $("#tu-count").html(resp.data.count);
    var tuScope = $('#tu-scope');
    tuScope.empty();
    resp.data.results.forEach(function (it) {
      tuScope.append(getMetaPanel(it));
    }
    );
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $tScope = $('#tu-pagination-scope');
      $tScope.empty();
      $tScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getUnconducted(pageNo, perPage);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function getUnconductedSort(page, perPage,isAsc) {
  var url='mlplatform_api_v1:task_list_my_st_unc_des';
  if(isAsc)
    url='mlplatform_api_v1:task_list_my_st_unc_asc';
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve(url), {
    'page':page,
  }).done(function (resp) {
    var taScope = $('#tu-scope');
    taScope.empty();
    resp.data.results.forEach(function (it) {
      taScope.append(getMetaPanel(it));
    });
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $pScope = $('#tu-pagination-scope');
      $pScope.empty();
      $pScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getUnconductedSort(pageNo, perPage,isAsc);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function getRunning(page, perPage) {
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve('mlplatform_api_v1:task_list_my_st_run'), {
    'page':page,
  }).done(function (resp) {
    $("#tr-count").html(resp.data.count);
    var trScope = $('#tr-scope');
    trScope.empty();
    resp.data.results.forEach(function (it) {
      trScope.append(getMetaPanel(it));
    });
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $dScope = $('#tr-pagination-scope');
      $dScope.empty();
      $dScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getRunning(pageNo, perPage);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function getRunningSort(page, perPage,isAsc) {
  var url='mlplatform_api_v1:task_list_my_st_run_des';
  if(isAsc)
    url='mlplatform_api_v1:task_list_my_st_run_asc';
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve(url), {
    'page':page,
  }).done(function (resp) {
    var taScope = $('#tr-scope');
    taScope.empty();
    resp.data.results.forEach(function (it) {
      taScope.append(getMetaPanel(it));
    });
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $pScope = $('#tr-pagination-scope');
      $pScope.empty();
      $pScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getRunningSort(pageNo, perPage,isAsc);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function getCompleted(page, perPage) {
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve('mlplatform_api_v1:task_list_my_st_com'), {
    'page':page,
  }).done(function (resp) {
    $("#tc-count").html(resp.data.count);
    var tcScope = $('#tc-scope');
    tcScope.empty();
    resp.data.results.forEach(function (it) {
      tcScope.append(getMetaPanel(it));
    });
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $dScope = $('#tc-pagination-scope');
      $dScope.empty();
      $dScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getCompleted(pageNo, perPage);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

function getCompletedSort(page, perPage,isAsc) {
  var url='mlplatform_api_v1:task_list_my_st_com_des';
  if(isAsc)
    url='mlplatform_api_v1:task_list_my_st_com_asc';
  page = page || 1;
  perPage = perPage || PER_PAGE;
  $.get(Urls.resolve(url), {
    'page':page,
  }).done(function (resp) {
    var taScope = $('#tc-scope');
    taScope.empty();
    resp.data.results.forEach(function (it) {
      taScope.append(getMetaPanel(it));
    });
    CURRENT_PAGE = page;
    TOTAL_PAGE = resp.data.total_pages;
    if (TOTAL_PAGE > 1) {
      var $pScope = $('#tc-pagination-scope');
      $pScope.empty();
      $pScope.append(getPaginationNav(CURRENT_PAGE, TOTAL_PAGE, 5, function (pageNo) {
        getCompletedSort(pageNo, perPage,isAsc);
      }));
    }
  }).fail(function () {
    window._jqHandled = true;
  });
}

$(function () {
  var all = $('#task-all'), unconducted = $('#task-unconducted'), running = $('#task-running'),completed=$("#task-completed");
  getAll(1, 5);
  getUnconducted(1,5);
  getRunning(1,5);
  getCompleted(1,5);

  $("#ta-time-forward").click(function () {
    getAllSort(1,5,true);
  });
  $('#ta-time-reverse').click(function () {
    getAllSort(1,5,false);
  });
  $("#tu-time-forward").click(function () {
    getUnconductedSort(1,5,true);
  });
  $('#tu-time-reverse').click(function () {
    getUnconductedSort(1,5,false);
  });
  $("#tr-time-forward").click(function () {
    getRunningSort(1,5,true);
  });
  $('#tr-time-reverse').click(function () {
    getRunningSort(1,5,false);
  });
  $("#tc-time-forward").click(function () {
    getCompletedSort(1,5,true);
  });
  $('#tc-time-reverse').click(function () {
    getCompletedSort(1,5,false);
  });
});
